package com.explorex.infra.puma.gateway.netty.rrmp;


import com.explorex.infra.puma.gateway.netty.common.AbstractBaseServer;
import com.explorex.infra.puma.gateway.netty.common.enums.EnumUserStatus;
import com.explorex.infra.puma.gateway.netty.rrmp.MessageCenter;
import com.explorex.infra.puma.gateway.netty.ws.utils.SocketUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: JacceYang
 * @createTime: 2022/09/06 19:46
 * @description: 事件处理实现类
 */
@Slf4j
public class DefaultRTcpSocketEvent implements RTcpSocketEvent {

    private final MessageCenter messageCenter;

    public DefaultRTcpSocketEvent(MessageCenter messageCenter) {
        this.messageCenter = messageCenter;
    }

    @Override
    public void onOpenEvent(AbstractBaseServer server, RTcpSession session) {
        session.setLocalIp(SocketUtil.getLocalIp(session.channel()));
    }

    @Override
    public void onCloseEvent(AbstractBaseServer server, RTcpSession session) {
        if (session == null || StringUtils.isBlank(session.userId()) || StringUtils.isBlank(session.domain())) {
            return;
        }
        EnumUserStatus userStatusBeforeChange = EnumUserStatus.getUserStatus(session.userStatus());
        session.setStatus(EnumUserStatus.OFFLINE.getKey());

    }

    @Override
    public void OnErrorEvent(RTcpSession session) {
    }

    @Override
    public void onMessageEvent(AbstractBaseServer server, RTcpSession session, RrmpMessage msg) {
        long startTime = System.currentTimeMillis();
        Throwable throwable = null;
        try {
            RrmpMessage rrmpMessageResp = messageCenter.processMessage(session, msg);
            responseMessage(session, rrmpMessageResp);
        } catch (Exception e) {
            throwable = e;
            log.error("onMessageEvent exception msg={}", msg, e);
        } finally {
            session.refresh(false);

        }
    }

    private void responseMessage(RTcpSession session, RrmpMessage rrmpMessage) {
        if (rrmpMessage != null && session.canWrite()) {
            session.sendMessage(rrmpMessage);
        }
    }
}
